﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Models;
using SMARTMobile.Models.Local;
using SMARTMobile.WinPhone;
using System.Windows.Media;
using SMARTMobile.Services.SMARTMobileServiceReference;

namespace SMARTMobile.Views
{
    public partial class DSKhachHangPage
    {
        private float longtitude, latitude;
        private string cMode = "MCP";
        private ObservableCollection<TCARCUST> _customerOnTuyenList;
        private Brush originalBrush;
        private List<TCARCUST> _allCustomerList;
        private List<string> _custKeyShopList;
        private ReloadDataSmartPhoneSoapClient _proxy;

        /// <summary>
        /// double longtitude, double latitude
        /// </summary>
        public DSKhachHangPage()
        {
            InitializeComponent();
            this.BusyIndicator.IsRunning = true;
            ////this._customerOnTuyenList = new ObservableCollection<TCARCUST>(GetTCARCUST().OrderBy(x => x.Customername));
            //this.KhachHangAutoComplete.SuggestionsSource = this._customerOnTuyenList;
            ////this.KhachHangListBox.ItemsSource = this._customerOnTuyenList;

            // Default TUYEN
            originalBrush = this.GPS.Background;
            this._proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
            SmartMobileDBContext smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            smartMobileContext.CreateIfNotExists();

            this._allCustomerList = smartMobileContext.TCARCUST.OrderBy(x => x.Customerkey).ToList();
            this._custKeyShopList = smartMobileContext.Shopvisit.Select(x => x.CustomerKey).ToList();

            this.GetTuyenCust_OnClick(null, null);
            this.BusyIndicator.IsRunning = false;
        }

        private List<TCARCUST> GetTCARCUST()
        {
            try
            {
                var listTCARCUST = from t in this._allCustomerList
                                   where !this._custKeyShopList.Contains(t.Customerkey)
                                   select t;

                return listTCARCUST.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void KhachHangListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (KhachHangListBox.SelectedItem != null)
            {
                // Lay dia chi khach hang
                string diachi = string.Empty;
                if (KhachHangListBox.SelectedItem is TCARCUST)
                {
                    var selectedCus = KhachHangListBox.SelectedItem as TCARCUST;
                    GlobalInformation.SelectedTCARCUS = selectedCus;
                    diachi = selectedCus.Address;
                    selectedCus.Lat = this.latitude.ToString();
                    selectedCus.Long = this.longtitude.ToString();

                    SmartMobileDBContext smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);

                    // It will copy from local to iso
                    smartMobileContext.CreateIfNotExists();

                    var currentCUs = smartMobileContext.TCARCUST.FirstOrDefault(x => x.Customerkey == selectedCus.Customerkey);
                    currentCUs.Lat = this.latitude.ToString();
                    currentCUs.Long = this.longtitude.ToString();
                    string dateNow = DateTime.Now.ToShortDateString();
                    Shopvisit currentShopvisit = smartMobileContext.Shopvisit.FirstOrDefault(
                            x => x.CustomerKey == selectedCus.Customerkey && x.DateVisit == dateNow);
                    if (currentShopvisit == null)
                    {
                        currentShopvisit = new Shopvisit
                        {
                            CustomerKey = selectedCus.Customerkey,
                            Lat = currentCUs.Lat,
                            Long = currentCUs.Long,
                            DateVisit = dateNow,
                            ID_PK = Guid.NewGuid(),
                            StartTime = DateTime.Now.ToString(),
                            CMode = this.cMode
                        };

                        smartMobileContext.Shopvisit.InsertOnSubmit(currentShopvisit);
                    }
                    else
                    {
                        currentShopvisit.Lat = currentCUs.Lat;
                        currentShopvisit.Long = currentCUs.Long;
                        currentShopvisit.DateVisit = dateNow;
                        currentShopvisit.StartTime = DateTime.Now.ToString();
                        currentShopvisit.CMode = this.cMode;
                    }

                    smartMobileContext.SubmitChanges();

                    this._proxy.UploadShopvisitAsync(currentShopvisit.CustomerKey, currentShopvisit.Lat ?? string.Empty, currentShopvisit.Long ?? string.Empty,
                        currentShopvisit.DateVisit ?? string.Empty, GlobalInformation.ArSaleSPType.Usercode ?? string.Empty, currentShopvisit.StartTime ?? string.Empty,
                        currentShopvisit.EndTime ?? currentShopvisit.StartTime, GlobalInformation.SiteCode ?? string.Empty, currentShopvisit.CMode ?? string.Empty);
                }

                ////DataSourceService.Current.Write<List<SqlARCUST>>("TCARCUST", "SqlARCUSTList", GlobalInformation.DSKhachHang);

                ////smartMobileContext.IMAGECUSTOMER.DeleteOnSubmit(currentImageCustomer);
                ////smartMobileContext.SubmitChanges();

                GlobalInformation.StateImageType = 0;

                NavigationService.Navigate(new Uri("/Views/CapNhatKhachHangPage.xaml?msg=" + "IsGPS", UriKind.Relative));
            }
        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string value;
            if (NavigationContext.QueryString.TryGetValue("longtitude", out value))
            {
                if (!string.IsNullOrEmpty(value))
                {
                    longtitude = float.Parse(value);
                }
            }

            if (NavigationContext.QueryString.TryGetValue("latitude", out value))
            {
                if (!string.IsNullOrEmpty(value))
                {
                    latitude = float.Parse(value);
                }
            }
        }

        // GPS
        private void GetGPSCust_OnClick(object sender, RoutedEventArgs e)
        {
            this.cMode = "GPS";
            var listTCARCUST = from t in this._allCustomerList
                               where this._custKeyShopList.Contains(t.Customerkey)
                               select t;

            this.KhachHangListBox.ItemsSource = new ObservableCollection<TCARCUST>(listTCARCUST);

            this.GPS.Background = new SolidColorBrush(Colors.Orange);
            this.Tuyen.Background = originalBrush;
            this.All.Background = originalBrush;
        }

        // Tuyen
        private void GetTuyenCust_OnClick(object sender, RoutedEventArgs e)
        {
            this.cMode = "MCP";
            var listTCARCUST = from t in this._allCustomerList
                               where !this._custKeyShopList.Contains(t.Customerkey)
                               select t;
            if (listTCARCUST.Count() > 0)
            {
                List<TCARCUST> resultList = new List<TCARCUST>();
                switch ((int)DateTime.Now.DayOfWeek)
                {
                    // Monday
                    case 1:
                        {
                            resultList = listTCARCUST.Where(x => x.T2 == "1").ToList();
                            break;
                        }
                    case 2:
                        {
                            resultList = listTCARCUST.Where(x => x.T3 == "1").ToList();
                            break;
                        }
                    case 3:
                        {
                            resultList = listTCARCUST.Where(x => x.T4 == "1").ToList();
                            break;
                        }
                    case 4:
                        {
                            resultList = listTCARCUST.Where(x => x.T5 == "1").ToList();
                            break;
                        }
                    case 5:
                        {
                            resultList = listTCARCUST.Where(x => x.T6 == "1").ToList();
                            break;
                        }
                    case 6:
                        {
                            resultList = listTCARCUST.Where(x => x.T7 == "1").ToList();
                            break;
                        }
                }

                this.KhachHangListBox.ItemsSource = new ObservableCollection<TCARCUST>(resultList);
            }

            this.GPS.Background = originalBrush;
            this.Tuyen.Background = new SolidColorBrush(Colors.Orange);
            this.All.Background = originalBrush;
        }

        // Tat Ca
        private void GetAllCust_OnClick(object sender, RoutedEventArgs e)
        {
            this.cMode = "ALL";
            this.KhachHangListBox.ItemsSource = this._allCustomerList;

            this.GPS.Background = originalBrush;
            this.Tuyen.Background = originalBrush;
            this.All.Background = new SolidColorBrush(Colors.Orange);
        }

        ////private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
        ////{
        ////    string searchText = this.SearchTextBox.Text.ToLower();
        ////    if (!string.IsNullOrWhiteSpace(searchText))
        ////    {
        ////        List<TCARCUST> resultList = new List<TCARCUST>();
        ////        resultList = this._customerOnTuyenList.Where(x => x.Customername.ToLower().Contains(searchText)
        ////                                             || x.ShopOwner.ToLower().Contains(searchText)
        ////                                             || x.Address.ToLower().Contains(searchText)
        ////                                             || x.Provice.ToLower().Contains(searchText)
        ////                                             || x.Town.ToLower().Contains(searchText)
        ////                                             || x.Street.ToLower().Contains(searchText)
        ////            ).ToList();
        ////        this.KhachHangListBox.ItemsSource = new ObservableCollection<TCARCUST>(resultList);
        ////    }
        ////    else
        ////    {
        ////        this.KhachHangListBox.ItemsSource = this._customerOnTuyenList;
        ////    }
        ////}

    }
}